﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using FX.CC.Andon.SMSPushService.MsgSvcRef;
using System.Configuration;

namespace FX.CC.Andon.SMSPushService
{
    public partial class SMSPushSvc : ServiceBase
    {
        const string port_idx_key = "PortIdx";
        const string baud_rate_key = "BaudRate";
        const string log_source = "SMS Push Service Log";
        //const string timeout_msg_template = "Andon通知\n车间:{0}\n设备编号:{1}\n设备名称:{2}\n类别:{3}\n明细:{4}\n触发时间:{5}";
        //const string helpreq_msg_template = "Andon求助\n车间:{0}\n设备编号:{1}\n设备名称:{2}\n类别:{3}\n明细:{4}\n求助人:{5}";
        const string process_timeout_msg_template_key = "ProcessTimeOutMsgTPL";
        const string sign_timeout_msg_template_key = "SignTimeOutMsgTPL";
        const string helpreq_msg_template_key = "HelpMsgTPL";
        Thread msgTh;
        MessageDataSvc msgSvc;

        DateTime lastGetTime;
        Encoding ecd;
        string processTimeoutMsgTemplate, signTimeoutMsgTemplate, helpReqMsgTemplate;


        public SMSPushSvc()
        {
            InitializeComponent();
            if (!EventLog.SourceExists(log_source))
                EventLog.CreateEventSource(log_source, "Ty SMS Push Service Log"); 
        }

        protected override void OnStart(string[] args)
        {
            string portIdxStr = ConfigurationManager.AppSettings[port_idx_key];
            string baudRateStr = ConfigurationManager.AppSettings[baud_rate_key];
            processTimeoutMsgTemplate = ConfigurationManager.AppSettings[process_timeout_msg_template_key];
            signTimeoutMsgTemplate = ConfigurationManager.AppSettings[sign_timeout_msg_template_key];
            helpReqMsgTemplate = ConfigurationManager.AppSettings[helpreq_msg_template_key];

            processTimeoutMsgTemplate = processTimeoutMsgTemplate.Replace("#","\n");
            signTimeoutMsgTemplate = signTimeoutMsgTemplate.Replace("#", "\n");
            helpReqMsgTemplate = helpReqMsgTemplate.Replace("#", "\n"); 

            int iPort = Convert.ToInt32(portIdxStr);
            uint bit = Convert.ToUInt32(baudRateStr);

            ecd = Encoding.GetEncoding("GB2312");
            int ret = SMS.SMSStartService(iPort, bit, 2, 8, 0, 0, ecd.GetBytes("card"));
#if DEBUG
            ret = 1;
            EventLog.WriteEntry(log_source, "短信服务调试版本!", EventLogEntryType.Warning);
#endif
            if (ret == 1)
            {
                EventLog.WriteEntry(log_source, "短信服务启动成功!", EventLogEntryType.Information);
            }
            else
            {
                EventLog.WriteEntry(log_source, "短信服务初始化失败！请检查GSM Modem是否正常工作，SIM卡是否正确放置，通讯参数是否正确配置！", EventLogEntryType.Error);
                throw new Exception("短信服务启动失败");
            }

            msgSvc = new MessageDataSvc();

            msgTh = new Thread(DoGetMsg);
            msgTh.IsBackground = true;
            msgTh.Start();
            lastGetTime = DateTime.Now;
        }

        protected override void OnStop()
        {
            try
            {
                EventLog.WriteEntry(log_source, "短信服务已停止!", EventLogEntryType.Warning);
                if (msgTh != null)
                {
                    msgTh.Abort();
                }
                SMS.SMSStopSerice();
            }
            catch (Exception ex) {
                EventLog.WriteEntry(log_source, ex.ToString(), EventLogEntryType.Error);
            }
        }

        void DoGetMsg()
        {
            Thread.Sleep(30000);
            while (true)
            {
                Thread.Sleep(5000);
                try
                {
                    var wrapper = msgSvc.GetMessage(this.lastGetTime);
                    this.lastGetTime = wrapper.GetTime;
                    StringBuilder sb = new StringBuilder();
                    sb.Append("消息推送给以下用户：");
                    sb.AppendLine();
                    bool sent = false;
                    foreach (var i in wrapper.MsgArr)
                    {
                        if (string.IsNullOrWhiteSpace(i.MobileNo))
                        {
                            continue;
                        }

                        sent = true;

                        string msg = string.Empty;
                        switch (i.MsgTypeObj)
                        {
                            case MsgType.ProcessTimeoutMsg:
                                //"Andon系统异常通知\n产线：{0}\n设备编号：{1}\n设备名称：{2}\n类别：{3}\n明细：{4}\n触发时间：{5}"
                                msg = string.Format(processTimeoutMsgTemplate, i.LineName, i.EqName, i.ETypeName, i.DetailName, i.StartTime.ToString("HH:mm"));
                                break;

                            case MsgType.SignTimeoutMsg:
                                //"Andon系统异常通知\n产线：{0}\n设备编号：{1}\n设备名称：{2}\n类别：{3}\n明细：{4}\n触发时间：{5}"
                                msg = string.Format(signTimeoutMsgTemplate, i.LineName, i.EqName, i.ETypeName, i.DetailName, i.StartTime.ToString("HH:mm"));
                                break;

                            case MsgType.HelpMsg:
                                //"Andon求助\n产线:{0}\n设备编号:{1}\n设备名称:{2}\n类别:{3}\n明细:{4}\n求助人:{5}";
                                msg = string.Format(helpReqMsgTemplate, i.LineName, i.EqName, i.ETypeName, i.DetailName, i.Sender);
                                break;

                            default:
                                break;
                        }
                        byte[] Msg = ecd.GetBytes(msg);
                        byte[] PhoneNo = ecd.GetBytes(i.MobileNo);
#if !DEBUG
                        SMS.SMSSendMessage(Msg, PhoneNo);
#endif
                        sb.Append("姓名：");
                        sb.Append(i.Receiver);
                        sb.Append("\t");
                        sb.Append("消息类型：");
                        sb.Append(i.MsgTypeObj.ToString());
                        sb.AppendLine();
                        System.Diagnostics.Debug.WriteLine(string.Format("短信已发送，姓名：{0}，手机号：{1}", i.Receiver, i.MobileNo));
                    }
                    if (sent)
                    {
                        EventLog.WriteEntry(log_source, sb.ToString(), EventLogEntryType.Information);
                    }
                }
                catch (Exception ex)
                {
                    EventLog.WriteEntry(log_source, ex.ToString(), EventLogEntryType.Error);
                }
            }
        } 
    }
}
